import nProgress from 'nprogress'
import 'nprogress/nprogress.css'
import store from './store'
import router, { asyncRoutes } from '@/router'

const whiteList = ['/login']
router.beforeEach(async(to, from, next) => {
  nProgress.start()
  if (store.state.user.token) {
    if (whiteList.includes(to.path)) {
      next('/')
      nProgress.done()
    } else {
      // if (JSON.stringify(store.state.user.userInfo) === '{}') {
      // if (!store.state.user.userInfo.userId) {
      if (!store.getters.userId) {
        const res = await store.dispatch('user/setUserInfoAction')
        if (res) {
          const filterRoutes = asyncRoutes.filter((item) => {
            return res?.roles?.menus.includes(item.name)
          })
          router.addRoutes([
            ...filterRoutes,
            // 404 page must be placed at the end !!!
            { path: '*', redirect: '/404', hidden: true }
          ])
          store.commit('user/setRoutesMutation', [
            ...filterRoutes,
            // 404 page must be placed at the end !!!
            { path: '*', redirect: '/404', hidden: true }
          ])
        }
        next(to.path)
      }
      return next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
      nProgress.done()
    } else {
      next('/login')
      nProgress.done()
    }
  }
})
router.afterEach(() => {
  nProgress.done()
  window.scrollTo(0, 0)
})
